package com.vhly.remoteapi;

import com.vhly.remoteapi.yahoo.contact.*;
import com.vhly.remoteapi.yahoo.contact.field.*;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;

/**
 * Created by IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 2010-12-5
 * Time: 0:02:25
 * Email: vhly@163.com
 */
public class Main {

    /*

     if accessToken expired, use
       oauth_session_handle to refresh
       oauth_authorization_expires_in   oauth_session_handle 's expired time is 
       xoauth_yahoo_guid user's GUID

     */

    public static void main(String[] args) {
        YahooClient client = new YahooClient();
        OAuthService oauth = client.getOAuthService();
        client.loadToken();
        Token accessToken = client.accessToken;
        if (accessToken == null) {
            Token token = oauth.getRequestToken();
            System.out.println("token = " + token);
            String rau = token.getOther("xoauth_request_auth_url");
            if (rau == null) {
                StringBuffer sb = new StringBuffer("https://api.login.yahoo.com/oauth/v2/request_auth?oauth_token=");
                sb.append(token.getToken());
                System.out.println("Authorization URL is " + sb.toString());
            } else {
                System.out.println("Authorization URL is " + rau);
            }
            System.out.print("Please Input the verify code:");
            InputStreamReader ir = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(ir);
            String verifyCode = null;
            try {
                verifyCode = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    ir.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (verifyCode != null) {
                accessToken = oauth.getAccessToken(token, new Verifier(verifyCode));
                String ex = accessToken.getOther("oauth_authorization_expires_in");
                long ct = System.currentTimeMillis();
                accessToken.addOther("oauth_authorization_expires_in", String.valueOf(ct + (Long.parseLong(ex) * 1000)));

                ex = accessToken.getOther("oauth_expires_in");
                accessToken.addOther("oauth_expires_in", String.valueOf(ct + (Long.parseLong(ex) * 1000)));
                client.accessToken = accessToken;
                client.saveToken();
            }
        } else {
            String ex = accessToken.getOther("oauth_expires_in");
            long ct = System.currentTimeMillis();
            long ed = Long.parseLong(ex);
            if (ed < ct) {
                ex = accessToken.getOther("oauth_authorization_expires_in");
                if (ex != null) {
                    ed = Long.parseLong(ex);
                    if (ed > ct) {
                        // refresh
                        String sh = accessToken.getOther("oauth_session_handle");
                        accessToken = oauth.getAccessToken(accessToken, sh);
                        client.accessToken = accessToken;
                        client.saveToken();
                    } else {
                        // new req
                    }
                }
            }
        }


        if (accessToken != null) {
            String xml = client.getMeGUID();
            System.out.println("xml = " + xml);
            xml = client.getContactSync("0");
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance("", Main.class.getClassLoader());
            DocumentBuilder builder = null;
            try {
                builder = factory.newDocumentBuilder();
                byte[] bytes = xml.getBytes("UTF-8");
                ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
                Document doc = builder.parse(bin);
                System.out.println("doc = " + doc);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("xml = " + xml);
            Vector<ContactObject> cos = new Vector<ContactObject>();
            Contact contact = new Contact();
            contact.status = Status.ADD;
            Field field = new Field();
            field.status = Status.ADD;
            field.type = FieldType.nickname;
            field.value = new TextField("vhly[FR]");
            contact.fields.add(field);
            cos.add(contact);
            xml = client.syncContacts(cos, "0");
            System.out.println("xml = " + xml);
        }
    }
}
